package interview;

public class Search {
	
	public int binarySearch(int[] array, int element){
		
		if(element<array[0] || element >array[array.length-1]){
			return -1;
		}else if(element ==array[0]){
			return 0;
		}else if(element == array[array.length-1]){
			return array.length-1;
		}
		int startIndx = 0;
		int endIndx = array.length-1;
		int elementIndx=-1;
		int midIndx = (startIndx+endIndx)/2;
		
		while(midIndx>startIndx && midIndx<endIndx){
			int nextElement = array[midIndx];
			if(nextElement==element){
				return midIndx;
			}else if(nextElement<element){
				startIndx = midIndx;
			}else{
				endIndx = midIndx;
			}
			
			if(midIndx==(endIndx-1)){
				break; 
			}
			//
			midIndx = (startIndx+endIndx)/2;
		}
		return elementIndx;
	}

}
